<template>
  <div class="camera-container">
    <video ref="video" autoplay></video>
    <button @click="takePhoto">Take Photo</button>
<!--    <canvas ref="canvas"></canvas>-->
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted} from 'vue';

const video = ref<HTMLVideoElement | null>(null);
const canvas = ref<HTMLCanvasElement | null>(null);

onMounted(() => {
  // 获取用户媒体（相机）权限并播放视频流
  navigator.mediaDevices.getUserMedia({video: true})
      .then(stream => {
        if (video.value) {
          video.value.srcObject = stream;
        }
      })
      .catch(error => {
        console.error("Error accessing camera:", error);
      });
});

function takePhoto() {
  if (canvas.value && video.value) {
    const context = canvas.value.getContext('2d');
    if (context) {
      canvas.value.width = video.value.videoWidth;
      canvas.value.height = video.value.videoHeight;
      context.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height);
      // 可以在这里将图像数据保存或处理
    }
  }
}
</script>

<style scoped>
.camera-container {
  height: 246px;
  width: 176px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

video, canvas {
   width: 100%;
  height: 100%;
}

button {
  margin-top: 10px;
}
</style>
